import React, {Component} from 'react'
import './index.css'
import store from '../../redux/store'
import {incrementActionCreator, decrementActionCreator} from "../../redux/count_action";

class Count extends Component {

  state = {
    delta: 1
  }


  componentDidMount() {
    store.subscribe(() => this.setState({}))
  }

  handleSelect = e => this.setState({delta: e.target.value*1})

  handleIncrement = () => store.dispatch(incrementActionCreator(this.state.delta))

  handleDecrement = () => store.dispatch(decrementActionCreator(this.state.delta))

  handleAddIfOdd = () => {
    const value = store.getState()
    if (value % 2 !== 0) {
      store.dispatch(incrementActionCreator(this.state.delta))
    }
  }

  handleAddDelay = () => {
    setTimeout(() => {
      store.dispatch(incrementActionCreator(this.state.delta))
    }, 300)
  }

  render() {
    const value = store.getState()
    return (
      <div>
        <h1>当前求和: {value}</h1>
        <select onChange={this.handleSelect}>
          <option value={1}>1</option>
          <option value={1}>2</option>
          <option value={1}>3</option>
        </select> &nbsp;
        <button onClick={this.handleIncrement}>increment</button> &nbsp;
        <button onClick={this.handleDecrement}>decrement</button> &nbsp;
        <button onClick={this.handleAddIfOdd}>addIfOdd</button> &nbsp;
        <button onClick={this.handleAddDelay}>addDelay</button> &nbsp;
      </div>
    )
  }
}

export default Count